package org.seed.mybatis.core.util;


import lombok.extern.slf4j.Slf4j;
import org.seed.mybatis.core.ext.exception.DatabaseConnectException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

@Slf4j
public class DbUtil {


    /**
     * 获取数据库类型
     */
    public static String getDialect(DataSource dataSource) {
        if (dataSource == null) {
            throw new NullPointerException("dataSource 不能为null");
        }
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            DatabaseMetaData metaData = conn.getMetaData();
            String productName = metaData.getDatabaseProductName();
            if (productName == null) {
                productName = "";
            }
            String driverName = metaData.getDriverName();
            if (driverName == null) {
                driverName = "";
            }
            String url = metaData.getURL();
            if (url == null) {
                url = "";
            }
            log.debug("Database  \uD83D\uDEAA:" + productName);
            productName = productName.toLowerCase();
            if (driverName.contains("mysql") || url.contains("mysql") || productName.contains("mysql")) {
                return "mysql";
            }
            if (driverName.contains("sqlite") || url.contains("sqlite") || productName.contains("sqlite")) {
                return "sqlite";
            }
            if (driverName.contains("postgresql") || url.contains("postgresql") || productName.contains("postgresql")) {
                return "postgresql";
            }
            if (driverName.contains("oracle") || url.contains("oracle") || productName.contains("oracle")) {
                return "oracle";
            }
            if (driverName.contains("sqlserver") || url.contains("sqlserver") || productName.contains("sqlserver") || productName.contains("microsoft")) {
                return "microsoftsqlserver";
            }
            return productName;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new DatabaseConnectException(e);
        } finally {

        }
    }
}
